package com.huluobo.user.pages

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemsIndexed
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.RoutePath
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import com.huluobo.user.R
import com.huluobo.user.UserIntent
import com.huluobo.user.UserViewModel
import com.huluobo.user.entity.ApproveEntity
import com.huluobo.user.entity.ApproveEntityItem
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/8/27.
 */

@Composable
fun ApproveListPage(navHostController: NavHostController, vm: UserViewModel = hiltViewModel()) {
//    val list = remember {
//        SnapshotStateList<ApproveEntityItem>()
//    }

    //修改paging需要更换数据源,接收时转化为一个懒加载的Paging数据源
    val list = vm.getPagingData().collectAsLazyPagingItems()

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    var index by remember {
        mutableStateOf(-1)
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取请假列表失败:${it.msg}")
                        Log.e("TagA", "获取请假列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
//                        if (it.type == StateType.DEFAULT) {
//                            list.clear()
//                            list.addAll((it.data as ApproveEntity).sortedByDescending { it.createTime })
//                        }

                        if (it.type == StateType.DELETE) {
                            if (index != -1) {
//                                list.removeAt(index)
                                ToastUtils.showLong("删除成功")
                            }
                        }
                    }
                }
            }
        }
        vm.sendIntent(UserIntent.GetApprove)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Column(Modifier.padding(10.dp)) {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", modifier = Modifier.clickable {
                navHostController.popBackStack()
            })

            Text(text = "请假列表")
            Text(text = "申请", modifier = Modifier
                .background(colorResource(id = R.color.orange), RoundedCornerShape(5.dp))
                .clickable {
                    navHostController.navigate(RoutePath.ADD_APPROVE)
                }
                .padding(10.dp, 5.dp)
            )
        }

        Spacer(modifier = Modifier.height(10.dp))
        Row(
            Modifier
                .fillMaxWidth()
                .background(colorResource(id = R.color.lightblue))
                .padding(10.dp),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            var sort = true
            Text(text = "类型", modifier = Modifier.clickable {
//                if (sort) {
//                    sort = false
//                    list.sortBy { it.type }
//                } else {
//                    sort = true
//                    list.sortByDescending { it.type }
//                }
            })
            Text(text = "开始时间", modifier = Modifier.clickable {
//                if (sort) {
//                    sort = false
//                    list.sortBy { it.startTime }
//                } else {
//                    sort = true
//                    list.sortByDescending { it.startTime }
//                }
            })
            Text(text = "结束时间", modifier = Modifier.clickable {
//                if (sort) {
//                    sort = false
//                    list.sortBy { it.endTime }
//                } else {
//                    sort = true
//                    list.sortByDescending { it.endTime }
//                }
            })
            Text(text = "审批状态", modifier = Modifier.clickable {
//                if (sort) {
//                    sort = false
//                    list.sortBy { it.status }
//                } else {
//                    sort = true
//                    list.sortByDescending { it.status }
//                }
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        LazyColumn(content = {
//            items(list) {
//                ApproveItem(entityItem = it, navHostController = navHostController)
//            }

            //代下标的items
//            itemsIndexed(list) { i, item ->
//                ApproveItem(entityItem = item, navHostController = navHostController, vm) {
//                    index = i
//                }
//            }

            itemsIndexed(list) { i, item ->
                if (item != null) {
                    ApproveItem(entityItem = item, navHostController = navHostController, vm) {
                        index = i
                    }
                }
            }
        }, verticalArrangement = Arrangement.spacedBy(10.dp))
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ApproveItem(
    entityItem: ApproveEntityItem,
    navHostController: NavHostController,
    vm: UserViewModel,
    onClick: () -> Unit
) {

    var isShow by remember {
        mutableStateOf(false)
    }

    Row(
        Modifier
            .fillMaxWidth()
            .background(color = colorResource(id = R.color.lightgray), RoundedCornerShape(10.dp))
            .padding(10.dp)
            .combinedClickable(
                onClick = {
                    val json = Gson().toJson(entityItem)
                    if (entityItem.status == "通过" || entityItem.status == "拒绝") {
                        //如果请假状态是通过或者拒绝 进入详情页
                        navHostController.navigate(RoutePath.APPROVE + "/$json")
                    } else {
                        navHostController.navigate(RoutePath.COM_APPROVE + "/$json")
                    }
                },
                onLongClick = {
                    isShow = true
                }
            ),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        if (entityItem.type.isNullOrEmpty()) {
            Text(text = "缺失")
        } else {
            Text(text = entityItem.type)
        }

        if (entityItem.startTime.isNullOrEmpty()) {
            Text(text = "缺失")
        } else {
            Text(text = entityItem.startTime.substring(0, 10))
        }

        if (entityItem.endTime.isNullOrEmpty()) {
            Text(text = "缺失")
        } else {
            Text(text = entityItem.endTime.substring(0, 10))
        }

        val color =
            if (entityItem.status == "通过") Color.Green else if (entityItem.status == "拒绝") Color.Red else Color.Gray

        Text(
            text = entityItem.status, color = Color.White, modifier = Modifier
                .background(
                    color = color,
                    RoundedCornerShape(5.dp)
                )
                .padding(5.dp)
        )
    }

    if (isShow) {
        AlertDialog(onDismissRequest = {
            isShow = false
        }, dismissButton = {
            Text(text = "取消", modifier = Modifier.clickable {
                isShow = false
            })
        }, confirmButton = {
            Text(text = "确认", modifier = Modifier.clickable {
                onClick()
                vm.sendIntent(UserIntent.DeleteApprove(entityItem.id))
                isShow = false
            })
        }, text = {
            Text(text = "确认删除当前请假信息吗?")
        }, title = {
            Text(text = "删除提醒")
        })
    }
}